package com.le.tester.imooc.masterJUC.lock.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述：使用atomic的基本用法，这是一个原子类，是保证线程安全的
 */
public class AtomicIntegerDemo1 implements Runnable {
    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();

    //只是保证了可见性，并不具有原子性的操作,不具备线程安全
    private static volatile int basicCount = 0;

    public static void main(String[] args) throws InterruptedException {
        //类继承了Runnable接口之后，开启线程之后就会运行run方法
        AtomicIntegerDemo1 r = new AtomicIntegerDemo1();
        Thread thread1 = new Thread(r);
        Thread thread2 = new Thread(r);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println("原子类的结果:" + ATOMIC_INTEGER.get());
        System.out.println("普通类的结果:" + basicCount);
    }

    public void incrementAtomic() {
        //使用了原子类进行自增
        //ATOMIC_INTEGER.getAndIncrement();
        //自减会得到负数
        //ATOMIC_INTEGER.getAndDecrement();
        ATOMIC_INTEGER.getAndAdd(-10);
    }

    public synchronized void incrementBasic() {
        basicCount++;
    }

    @Override
    public void run() {
        //这边只是相当于新建了一个要运行的项目,可以和线程挂钩的方法
        for (int i = 0; i < 10000; i++) {
            incrementAtomic();
            incrementBasic();
        }
    }
}
